// CFont.cpp -- declarations for CFont.h
#include "CFont.h"
#include <cstring>
#include <iostream>
using namespace std;

CFont::CFont()
{
};

bool CFont::generateFont(char * pFile, unsigned int & texture_id, int texture_length, int char_length)
{
   if(!font_texture.LoadTGA(pFile)) return 0;
   if(font_texture.imageHeight!=texture_length || font_texture.imageWidth!=texture_length) return 0;
   font_texture.ID=texture_id;
   texture_id++;
   glGenTextures(1, &font_texture.ID);
   glBindTexture(GL_TEXTURE_2D, font_texture.ID);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
   glTexImage2D(GL_TEXTURE_2D, 0, 3, font_texture.imageWidth, font_texture.imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, font_texture.image);

   float cx, cy;
   font=glGenLists(256);
   for(GLuint i=0;i<256;i++)
   {
      // subdividing the texture into 256 squares
      cx=float((i)%char_length)/16.0f;
      cy=float((i*texture_length/256)/char_length)/16.0f;
      
      glNewList(font+i,GL_COMPILE);
      glBegin(GL_QUADS);
      glTexCoord2f(cx,1-cy-0.0625f);
      glVertex2i(0,0);
      glTexCoord2f(cx+0.0625f,1-cy-0.0625f);
      glVertex2i(char_length,0);
      glTexCoord2f(cx+0.0625f,1-cy);
      glVertex2i(char_length,char_length);
      glTexCoord2f(cx,1-cy);
      glVertex2i(0,char_length);
      glEnd();
      glTranslated(char_length*10/16,0,0);
      glEndList();
   }
   //delete [] pFile;
   return 1;
};

void CFont::glPrint(int x, int y, char * fmt, ...)
{
   if(fmt==NULL)
      return;
   char text[512];
   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); 
   glBindTexture(GL_TEXTURE_2D, font_texture.ID);
   glDisable(GL_DEPTH_TEST);
   glEnable(GL_BLEND);
   //glEnable(GL_COLOR_MATERIAL);
   glBlendFunc(GL_ONE,GL_SRC_ALPHA);
   
   glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   gluOrtho2D(0,1440,0,900); // feed screen height and width here
   glMatrixMode(GL_MODELVIEW);
   glPushMatrix();
   glLoadIdentity();
   
   glTranslated(x,y,0);
   va_list list;
      
   va_start(list, fmt);
   vsprintf(text, fmt, list);
   va_end(list);
   
   // look up glpushattrib if future display list problems arise 
   glListBase(font-32);
   glCallLists(strlen(text),GL_UNSIGNED_BYTE,text);
   glPopMatrix();
   
   glMatrixMode(GL_PROJECTION);
   glPopMatrix();
   glMatrixMode(GL_MODELVIEW);
   glDisable(GL_BLEND);
   glEnable(GL_DEPTH_TEST);
   glBindTexture(GL_TEXTURE_2D, 0);
};

CFont::~CFont()
{
   glDeleteLists(font,256);
   font_texture.FreeImage();       
};
